<template>
  <view class="container">
    <!-- 收货 -->
    <uni-forms
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="top"
      label-width="75vw">
      <uni-forms-item name="isTransportCode" label="请选择有无交委电子运单" required>
        <!-- <view class="title"></view> -->
        <uni-data-checkbox
          v-model="formData.isTransportCode"
          :localdata="optionItems"
          @change="onChangeInoutType">
        </uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="transportCode" label="请扫描或输入电子运单" v-if="formData.isTransportCode == 1" required>
        <!-- <view class="title"></view> -->
        <uni-easyinput suffixIcon="scan" type="text" v-model="formData.transportCode" @change="onChangeTransportCode" maxlength="24" placeholder="请输入" @iconClick="onClickScanCode" />
      </uni-forms-item>
      <uni-forms-item name="carNo" :label="`请${carList.length > 0 ? '选择' : '输入'}承运车辆车牌号`" required>
        <!-- <view class="title">请{{carList.length > 0 ? '选择' : '输入'}}承运车辆车牌号</view> -->
        <uni-data-select
          v-model="formData.carNo"
          :localdata="carList"
          v-if="carList.length > 0"
          style="background:#fff"
        ></uni-data-select>

        <uni-easyinput v-if="carList.length == 0 || formData.isTransportCode == 2" type="text" v-model="formData.carNo" placeholder="请输入" />
      </uni-forms-item>
      
      <uni-forms-item name="traceUrlUnicode" label="请扫描危险化学品追溯码" required>
        <!-- <view class="title"></view> -->
        <view class="scanCode" @click="onClickTraceUrlUnicode">
          <uni-icons type="scan" size="80"></uni-icons>
        </view>
        <view style="margin-top: 10upx;">
          <uni-easyinput type="text" v-if="codeFlag" v-model="formData.traceUrlUnicode" placeholder="请输入追溯码" @blur="onClickTraceCode" />
        </view>
      </uni-forms-item>
      <view class="box">
        <view class="tips">扫描中: 若扫描失败可切换<text class="blue" @click="codeFlag = true">输入追溯码登记号</text></view>
        <view class="tips">收货前: 确认收货数量</view>
        <view class="list" v-if="business">
          <view class="mtitle">
            <h3>收货单货品</h3>
            <a href="javascript:;" class="del" @click="onClickDelect">
              <uni-icons type="trash-filled" size="20" style="position: relative;top:3upx;" color="#333"></uni-icons>删除
            </a>
          </view>
          <view class="bd">
            <ul>
              <li>
                <span>追溯登记号：</span>
                <span>{{ business.traceUrlUnicode }}</span>
                <!-- <span class="icon">
                  <uni-icons type="trash-filled" size="20"></uni-icons>
                </span> -->
              </li>
              <li>
                <span>货品名称：</span>
                <span>{{ business.merchandiseName }}</span>
              </li>
              <!-- 发货数量不显示 -->
              <!-- <li>
                <span>发货数量：</span>
                <span>123123123</span>
                <span class="icon">
                  <uni-icons type="contact" size="20"></uni-icons>
                </span>
              </li> -->
              <!-- <li>
                <span>规格：</span>
                <span>{{ business.unit }}</span>
              </li> -->
              <li>
                <span>追溯批次号：</span>
                <span>{{ business.traceBatchNo }}</span>
              </li>
              <li>
                <span>收货数量：</span>
                <span style="display: flex;">
                  <uni-number-box :min="0" :max="1000000" v-model="business.amount" /> &nbsp;&nbsp;kg
                </span>
              </li>
              <li>
                <span>收货用途：</span>
                <span>
                  <!-- {{ business.receivePurpose }} -->
                  <uni-data-select
                    v-model="formData.receivePurpose"
                    :localdata="purposeAll"
                    style="width:420upx;"
                    :clear="false"
                   ></uni-data-select>
                </span>
              </li>
              <li>
                <span>货品来源：</span>
                <span>{{ business.merchandiseSource ? business.merchandiseSource : '扫码加入' }}</span>
              </li>
              <li>
                <span>收货企业：</span>
                <span>
                  <uni-data-select
                    v-model="formData.receiveEnterpriseName"
                    :localdata="enterpriseList"
                    style="width:425upx;"
                    :clear="false"
                   ></uni-data-select>
                </span>
              </li>
            </ul>
          </view>
        </view>
      </view>
    </uni-forms>
    
    <div class="ft">
      <button type="primary" @click="handleSubmit">收货</button>
    </div>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { apis as APIS } from "@/api/yiqiyipin.js";
import { router } from "@/router/index.js";

const formData = ref({
  carNo: '',
  transportCode: '',  // 31000203232408220021686526
  isToOuter: '',  
  isTransportCode:  1,
  traceUrlUnicode: ''  // 20241213124332833
  // https://dcrs.dwork-park.top/qr/4UMedY?info=10001%2C1002%2C1003%7C%7C133123
});

const rules = ref({
  isTransportCode: {
    rules: [{ required: true, errorMessage: "请选择有无交委电子运单" }],
  },
  transportCode: {
    rules: [{ required: true, errorMessage: "请扫描或输入电子运单" }],
  },
  carNo: {
    rules: [{ required: true, errorMessage: "请输入承运车辆车牌号" }],
  },
  isToOuter: {
    rules: [{ required: true, errorMessage: "是否发往外省市" }]
  }
});

const optionItems = [
  {
    value: 1,
    text: "有交委电子运单",
  },
  {
    value: 2,
    text: "无交委电子运单",
  }
]

const optionItemsIsToOuter = [
  {
    value: 1,
    text: "是",
  },
  {
    value: 0,
    text: "否",
  }
]

const carList = ref([])

const onChangeInoutType = () => {
  carList.value = []
  business.value = ''
  formData.value.carNo = ''
  formData.value.transportCode = ''
}

// 输入电子运单号
const onChangeTransportCode = (e) => {
  if(e){
    APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
      if(res.code === 200){
        formData.value = {
          ...formData.value,
          ...res.data
        }
      }
    });
  }
}

// 根据加密车牌，查询匹配车牌号
const onClickScanCode = (e) => {
  // 扫码出来的内容，车牌号传给接口
  // let str = '02$01$310002032324082200216865$沪FF**63,黄色$王磊,320826******143430,陈太露,321323******243337$mAp4VAYDZKA/j5uMBioanmG4RTBnZbluq+wZmDeGm8iS85i2F70J6JVMy57BeJa4dHW2cbFnrreUDr3U9nFLkA=='

  // formData.value.transportCode = str.split('$')[2]
  // let carNo = str.split('$')[3].split(',')[0]

  // // 根据加密车牌，查询匹配车牌号
  APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
    if(res.code === 200){
      formData.value = res.data
    }
  });
  
  uni.scanCode({
    onlyFromCamera: false, // 是否只从相机扫码，不从相册选择图片
    scanType: ['qrCode'], // 扫描的类型
    success: function (res) {
      console.log('扫描结果：', res.result);
      console.log('扫描条码类型：', res.scanType);
      console.log('字符集：', res.charSet);
      console.log('路径：', res.path); // 当所扫的码为小程序码时会返回此项
      
      // 扫码出来的内容，车牌号传给接口
      // 02$01$310002032324082200216865$沪FF**63,黄色$王磊,320826******143430,陈太露,321323******243337$mAp4VAYDZKA/j5uMBioanmG4RTBnZbluq+wZmDeGm8iS85i2F70J6JVMy57BeJa4dHW2cbFnrreUDr3U9nFLkA==
      
      if(res.result){
        formData.value.transportCode = res.result.split('$')[2]
        let carNo = res.result.split('$')[3].split(',')[0]

        // 根据加密车牌，查询匹配车牌号
        APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
          if(res.code === 200){
            formData.value = res.data
          }
        });
      }
    },
    fail: function (err) {
      console.error('扫码失败：', err);
      uni.showToast({
        title: `扫码失败：${err}`,
      });
    },
    complete: function () {
      console.log('扫码操作完成');
    }
  });
}

// 根据追溯码url查询货品详情
const business = ref()
const onClickTraceUrlUnicode = (e) => {
  uni.scanCode({
    onlyFromCamera: false, // 是否只从相机扫码，不从相册选择图片
    scanType: ['qrCode'], // 扫描的类型
    success: function (res) {
      console.log('扫描结果：', res.result);
      console.log('扫描条码类型：', res.scanType);
      
      if(res.result){
        // 根据追溯码url，查货单信息
        APIS.byTraceUrl({traceUrl: res.result}).then((res) => {
          if(res.code === 200){
            business.value = res.data
          }
        });
      }
    },
    fail: function (err) {
      console.error('扫码失败：', err);
      uni.showToast({
        title: `扫码失败：${err}`,
      });
    },
    complete: function () {
      console.log('扫码操作完成');
    }
  });

  // business.value = ''
  // APIS.byTraceUrl({traceUrl: 'https://dcrs.dwork-park.top/qr/4UMedY?info=10001%2C1002%2C1003%7C%7C133123'}).then((res) => {
  //   if(res.code === 200){
  //     business.value = res.data
  //   }
  // });
}

// 输入追溯码查询
const onClickTraceCode = (e) => {
  if(formData.value.traceUrlUnicode){
    business.value = ''
    APIS.merchandiseInfoId(formData.value.traceUrlUnicode).then((res) => {
      if(res.code === 200){
        business.value = res.data
      }
    });
  }
}

const codeFlag = ref(false)

// 收货企业
const enterpriseList = ref([])
const fGetEnterpriseList = (e) => {
  APIS.enterpriseList().then((res) => {
    if(res.code === 200){
      res.data.map(item => {
        enterpriseList.value.push({
          value: item,
          text: item.enterpriseName
        })
      })
    }
  });
}
fGetEnterpriseList()


// 收货用途
const purposeAll = ref([])
const fGetPurposeAll = (e) => {
  APIS.purposeAll().then((res) => {
    if(res.code === 200){
      Object.keys(res.data).forEach(key => {
        purposeAll.value.push({
          value: key,
          text: key
        })
      });
    }
  });
}
fGetPurposeAll()

const onClickDelect = () => {
  business.value = ''
}

const formRef = ref();
const handleSubmit = (data) => {
  formRef.value.validate().then((res) => {
    let data = {
      ...business.value,
      ...formData.value,
      receiveEnterpriseName: formData.value.receiveEnterpriseName.enterpriseName,
      receiveEnterpriseId: formData.value.receiveEnterpriseName.id
    }
    
    APIS.receiveBusinessAdd(data).then((res) => {
      if(res.code === 200){
        uni.showToast({
          title: '收货成功！',
          icon: 'success',
          duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
          mask:false, // 是否显示透明蒙层，防止触摸穿透，默认：false
        });
        setTimeout(() => {
          router.toPage({
            path: "/pages/home/index"
          });
        }, 2000);
      }
    });
  })
  .catch((err) => {
    console.log("表单错误信息", err);
  });
}

onMounted(() => {});
</script>

<style lang="scss" scoped>
.container {
  padding: 20upx;
  background: #fff;

  .title{
    font-weight: 500;
    font-size: 30upx;
    padding-bottom: 10upx;
  }

  .scanCode{
    width: 100%;
    height: 300upx;
    background: #fff;
    display: flex;
    border-radius: 8upx;
    border: 1upx solid #ccc;
    justify-content: center;
    align-items: center;
  }

  .blue{
    color: blue;
  }
  .tips{
    color: #000;
    font-size: 24upx;
    padding-bottom: 8upx;
  }
  .list{
    background: #fff;
    margin-top: 30upx;
    border-radius: 10upx;
    border: 1upx solid #e1e1e1;

    .mtitle{
      padding: 20upx 30upx;
      display: flex;
      justify-content: space-between;
      border-bottom: 1upx solid #e1e1e1;

      h3{
        font-size: 28upx;
      }

      .del{
        color: #f00;
        text-decoration: none;
      }
    }
    ul{
      padding: 20upx 10upx;
      li{
        list-style: none;
        color: #666;
        line-height: 42upx;
        display: flex;
        align-items: center;
        margin-bottom: 15upx;

        span{
          font-size: 24upx;
        }

        span:nth-child(1){
          width: 210upx;
          text-align: right;
          display: inline-block;
          padding-right: 10upx;
        }
        .icon{
          position: relative;
          top: 3upx;
          left: 10upx;
        }
      }
    }
  }

  .ft{
    width: 100%;
    margin-top: 20upx;
  }
}

:deep .uni-select__input-box{
  overflow: hidden;
}

.box{
  color: #000;
}
</style>
